package com.wf.demo.sys.controller;

import com.wf.demo.info.util.Result;
import com.wf.demo.sys.annotation.SysLog;
import com.wf.demo.sys.pojo.User;
import com.wf.demo.sys.service.UserService;
import com.wf.demo.sys.shiro.ShiroUtils;
import com.wf.demo.sys.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.HtmlUtils;

import java.util.List;

/**
 * @Auther: wf  UserController用来测试访问，权限全部采用注解的方式。
 * @Date: 2019/12/20 12:36
 * @Description:
 */
@Slf4j
@RestController
public class UserController {
    @Autowired
    UserService userService;

    @GetMapping("/users")
    @RequiresPermissions("sys:user")
    public List<User> list(){
       /* List<User> users=userService.list();
         User superUser=userService.get(1l);
         //超级管理员不会显示在前端
        users.remove(superUser);*/
        return userService.list();
    }

    @GetMapping("/users/{id}")
    @RequiresPermissions("sys:user")
    public Object get(@PathVariable("id")long id ){
       User bean =userService.get(id);
        return bean;
    }

    @SysLog("保存用户")
    @PostMapping("/users")
    @RequiresPermissions("sys:user")
    public Object register(@RequestBody User user) {
        String name =  user.getUsername();
        String password = user.getPassword();
        name = HtmlUtils.htmlEscape(name);
        user.setUsername(name);
        boolean exist = userService.isExist(name);
        if(exist){
            String message ="用户名已经被使用,不能使用";
            return Result.addFail(message);
        }
        //产生随机数盐
        String salt = new SecureRandomNumberGenerator().nextBytes().toString();
        log.info("盐是"+salt);
        //加密
        int times = ShiroUtils.hashIterations;
        String algorithmName = ShiroUtils.hashAlgorithmName;
        //生成加密后的密码
        String encodedPassword = new SimpleHash(algorithmName, password, salt, times).toString();
        user.setSalt(salt);
        //加密后的密码储存起来
        user.setPassword(encodedPassword);
        userService.add(user);
        return Result.addSuccess(user);
    }

    @SysLog("修改用户")
    @PutMapping("/users")
    @RequiresPermissions("sys:user")
    public Object update(@RequestBody User bean) throws Exception{
        String name = bean.getUsername();
        //取出新密码
        String password=bean.getPassword();

        boolean exist = userService.isExist(bean);
        if(exist){
            String message ="用户名已经被使用,不能使用";
            return Result.addFail(message);
        }
        //取出数据库原本的user
        User user=userService.getByName(name);
        //取出随机数盐
        String salt =user.getSalt() ;
        //加密
        int times = ShiroUtils.hashIterations;
        String algorithmName = ShiroUtils.hashAlgorithmName;

        if (StringUtil.isBlank(bean.getPassword())){
            //如果用户输入密码为空,直接替换为原密码
            bean.setPassword(user.getPassword());
            bean.setSalt(salt);
            System.out.println("输入密码为空");
        }
        else{
            //将新密码加密的密码
            String encodedPassword = new SimpleHash(algorithmName, password, salt, times).toString();
            //给修改后的bean增加盐和加密的密码
            bean.setSalt(salt);
            //加密后的密码储存起来
            bean.setPassword(encodedPassword);
        }
       //更新
        userService.update(bean);
        return Result.addSuccess(bean);
    }

    @SysLog("删除用户")
    @DeleteMapping("/users/{id}")
    @RequiresPermissions("sys:user")
    public Object  delete(@PathVariable("id")long id ){
        if(id == 1)
            return Result.error(-1,"系统管理员不能删除");
        userService.delete(id);
        return  Result.error(200,"删除成功");
    }
    //修改密码
    @PostMapping("/users/psw")
    @RequiresPermissions("sys:user")
    public Object  updatePassword(@RequestBody User bean){
        long id=bean.getId();
        String newPassword=bean.getPassword();
       //取出数据库原本的user
       User user=userService.get(id);
       //取出随机数盐
       String salt =user.getSalt() ;
       //加密
       int times = ShiroUtils.hashIterations;
       String algorithmName = ShiroUtils.hashAlgorithmName;

       if (StringUtil.isBlank(newPassword)){
           //如果用户输入密码为空,直接替换为原密码
           return Result.addFail("输入的密码为空，修改失败");
       }
       else{
           //将新密码加密的密码
           String encodedPassword = new SimpleHash(algorithmName, newPassword, salt, times).toString();
           //加密后的密码储存起来
          user.setPassword(encodedPassword);
       }
       //更新
       userService.update(user);
       return Result.addSuccess(user);
    }
}
